package com.sc.core.util.translator;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import lombok.Data;
import lombok.Getter;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
@Component("baidu")
public class BaiduTranslationProviderImpl implements ITranslatorProvider {
    private static final Logger log = LoggerFactory.getLogger(BaiduTranslationProviderImpl.class);
    private final String url = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    private final Map<Lang, String> langMap = new HashMap<>() {{
        put(Lang.AUTO, "auto");
        put(Lang.EN, "en");
        put(Lang.ZH_CN, "zh");
    }};

    private final Configuration configuration;

    public BaiduTranslationProviderImpl(Configuration configuration) {
        this.configuration = configuration;
    }

    @SneakyThrows
    private String request(String text, String source, String target){
        String randomStr = "S" + new SecureRandom().nextInt(10000);
        URL obj = new URL(url + "?" + params(new HashMap<>() {{
            put("q", text);
            put("from", source);
            put("to", target);
            put("appid", configuration.getBaidu().getAppid());
            put("salt", randomStr);
            put("sign", sign(text, randomStr));
        }}));
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法 (GET, POST, PUT, DELETE, etc.)
        con.setRequestMethod("GET");

        // 可选: 设置请求头
        con.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        StringBuilder response = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } else {
            throw new RuntimeException("请求失败");
        }

        return response.toString();
    }

    private String params(Map<String, Object> params){
        StringBuilder stringBuffer = new StringBuilder();
        params.forEach((key, value) -> {
            if (!stringBuffer.isEmpty()) {
                stringBuffer.append("&");
            }
            stringBuffer.append(key).append("=");
            stringBuffer.append(URLEncoder.encode((String) value, StandardCharsets.UTF_8));
        });

        return stringBuffer.toString();
    }

    @SneakyThrows
    private String sign(String text, String randomStr){
        MessageDigest md = MessageDigest.getInstance("MD5");

        String data = configuration.getBaidu().getAppid() + text + randomStr + configuration.getBaidu().getSecret();

        byte[] messageDigest = md.digest(data.getBytes());  // 将输入字符串转换为字节数组并计算摘要

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest) {
            String hex = Integer.toHexString(0xff & b);  // 将字节转换为十六进制，并确保是两位的
            if (hex.length() == 1) {
                hexString.append('0');  // 如果是一位，在前面补0
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    @SneakyThrows
    @Override
    public String translation(String text, Lang source, Lang target) {
        String response = request(text, langMap.get(source), langMap.get(target));

        TranslationResponse responseObj = new ObjectMapper().readValue(response, TranslationResponse.class);

        return responseObj.getTransResult() == null ? "" : responseObj.getTransResult().get(0).getDst();
    }

    @SneakyThrows
    @Override
    public Map<String, String> translation(List<String> text, Lang source, Lang target) {
        String response = request(String.join("\n", text), langMap.get(source), langMap.get(target));
        log.info("baidu translation response: {}", response);
        TranslationResponse responseObj = new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE).readValue(response, TranslationResponse.class);
        HashMap<String, String> res = new HashMap<>();
        if (responseObj.getTransResult() != null) {
            responseObj.getTransResult().forEach(item -> res.put(item.getSrc(), item.getDst()));
        }

        return res;
    }

    @Data
    private static class TranslationResponse{
        private String from;
        private String to;
        private List<TranslationResult> transResult;
    }

    @Data
    private static class TranslationResult{
        private String src;
        private String dst;
    }
}
